//
//  AlbumDetailViewController.m
//  HuiYinMaster
//
//  Created by Icloud-Zhanyong on 2017/4/19.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "AlbumDetailViewController.h"
#import "AlbumDetailHeaderView.h"
#import "ZYShareView.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "SeverManager.h"
#import "AlbumDetailInfoTableViewCell.h"
#import "SoundListTableViewCell.h"
#import "AlbumBatchDownloadViewController.h"
#import "AlbumDetailSelectTableViewCell.h"
#import "AFNetWorking.h"


@interface AlbumDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property(nonatomic,strong)UIButton *detailButton;
@property(nonatomic,strong)UIButton *programButton;
@property(nonatomic,strong)NSArray * stateArray;
@property(nonatomic,assign)int i;
@property(nonatomic,assign)int size;
@property(nonatomic,assign)int total;
@end

@implementation AlbumDetailViewController

- (void)viewDidLoad {
    self.i = 0;
    self.size = 5;
    self.total = 0;
    [super viewDidLoad];
    [self createUI];
    [self loadData];
    [self addFooterRefresh];
}
-(NSMutableArray<VoiceListModel *> *)voiceListDataArray {
    if (_voiceListDataArray == nil) {
        _voiceListDataArray = [[NSMutableArray alloc]init];
    }
    return _voiceListDataArray;
}
//这个方法在哪里调用的？
-(void)XMRefreshLoadMore {
    self.i = (int)self.voiceListDataArray.count;
    [self loadData];
}


-(void)createUI{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"专辑详情";
    UIButton * shareAlbumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareAlbumBtn addTarget:self action:@selector(shareAlbumBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [shareAlbumBtn setImage:[UIImage imageNamed:@"nav_icon_share"] forState:UIControlStateNormal];
    [shareAlbumBtn sizeToFit];
    UIBarButtonItem * shareAlbumItem = [[UIBarButtonItem alloc]initWithCustomView:shareAlbumBtn];
    //空隙
    UIBarButtonItem * fixSpaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixSpaceItem.width = 17;
    UIButton * moreAlbumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreAlbumBtn addTarget:self action:@selector(moreAlbumBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [moreAlbumBtn setImage:[UIImage imageNamed:@"nav_icon_more"] forState:UIControlStateNormal];
    [moreAlbumBtn sizeToFit];
    UIBarButtonItem * moreAlbumItem = [[UIBarButtonItem alloc]initWithCustomView:moreAlbumBtn];
    
    self.navigationItem.rightBarButtonItems = @[moreAlbumItem,fixSpaceItem,shareAlbumItem];
    
    self.albumDetailHeaderView = [AlbumDetailHeaderView fastLoginView];
    self.albumDetailHeaderView.frame = CGRectMake(0, 0,SCREEN_WIDTH ,150);
    self.BaseTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    self.BaseTableView.tableHeaderView = self.albumDetailHeaderView;
    [self.albumDetailHeaderView.AlbumBatchDownloadButton addTarget:self action:@selector(AlbumBatchDownload) forControlEvents:UIControlEventTouchUpInside];
    //设置图片
    NSString * albumDetailImageStr = [NSString stringWithFormat:@"%@%@",port,self.self.AlbumDtailModel.imgUrl];
    NSURL * albumDetailImageUrl = [NSURL URLWithString:albumDetailImageStr];
    [self.albumDetailHeaderView.AlbumDetailImageView sd_setImageWithURL:albumDetailImageUrl];
    
    self.albumDetailHeaderView.AlbumTitleLabel.text = self.AlbumDtailModel.title;
    self.albumDetailHeaderView.AlbumClassifyLabel.text = [NSString stringWithFormat:@"分类:%@",self.AlbumDtailModel.label] ;
    self.albumDetailHeaderView.AlbumPlaytimes.text = [NSString stringWithFormat:@"播放:%i万",self.AlbumDtailModel.playTimes];
    self.albumDetailHeaderView.AlbumCreatTimeLabel.text = [self.AlbumDtailModel.createTime substringToIndex:10];
    self.BaseTableView.delegate = self;
    self.BaseTableView.dataSource = self;
    [self.view addSubview:self.BaseTableView];
    NSLog(@"专辑id%d",self.AlbumDtailModel.id);
    
}
-(void)loadData {
    NSDictionary * param = @{
                             @"i" : @(self.i),
                             @"size" : @(self.size),
                             @"albumId" : @(self.AlbumDtailModel.id)
                             };
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:appId forHTTPHeaderField:@"appId"];
    [manager POST:voiceList parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"专辑详情%@",responseObject);
        NSArray * array  = responseObject[@"data"];
        if (array.count > 0) {
            for (int j = 0;j < array.count;j++) {
                NSDictionary * dic = array[j];
                VoiceListModel * model = [[VoiceListModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                model.headerImageUrl = self.headerImgUrl;
                model.playID = j + self.total;
                NSLog(@"%d",model.playID);
                [self.voiceListDataArray addObject:model];
            }
            self.total += self.size;
            
            [self.BaseTableView reloadData];
        } else {
            self.noMoredata = YES;
        }
        self.isRefresh = NO;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        self.isRefresh = NO;
    }];
}

//设置是否选中详情按钮
bool infoBtnSelect = false;
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    _stateArray = @[@"详情",@"节目"];
    for (int i = 0; i < _stateArray.count; i++){
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake((tableView.contentSize.width / 2) * i, 0, tableView.contentSize.width / 2, 40);
        [btn setTitle:_stateArray[i] forState:UIControlStateNormal];
        btn.showsTouchWhenHighlighted = YES;
        btn.tag = i + 300;
        //按钮是否选中
        btn.selected = false;
        [btn addTarget:self action:@selector(btnChoose:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor whiteColor]];
        [btn setTitleColor:XMColor(108, 34, 42) forState:UIControlStateSelected];
        if (infoBtnSelect == YES && btn.tag == 300){
            btn.selected = YES;
        }else if (infoBtnSelect == false && btn.tag == 301) {
            btn.selected = YES;
        }
        [view addSubview:btn];
    }
    return view;
}
#pragma mark -批量下载
-(void)AlbumBatchDownload{
    AlbumBatchDownloadViewController * vc = [[AlbumBatchDownloadViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -按钮选中状态
-(void)btnChoose:(UIButton *)sender{
    for (int i = 0; i < _stateArray.count ; i++) {
        UIButton *btn = (UIButton *)[[sender superview]viewWithTag:300 + i];
        [btn setSelected:false];
    }
    UIButton *button = (UIButton *)sender;
    [button setSelected:YES];
    if (button.tag == 300){
        infoBtnSelect = YES;
    }else{
        infoBtnSelect = false;
    }
    [self.BaseTableView reloadData];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    //设置 title 区域高度
    return 40.f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (infoBtnSelect){
        return 1;
    }else
        return self.voiceListDataArray.count + 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (infoBtnSelect){
        AlbumDetailInfoTableViewCell * cell = [AlbumDetailInfoTableViewCell fastLoginView];
        cell.AlbumDetailInfoTitleLabel.text = _AlbumDtailModel.title;
        cell.AlbumDetailInfoContentLabel.text = _AlbumDtailModel.content;
        cell.selectionStyle = UITableViewCellAccessoryNone;
        return cell;
    }else if (indexPath.row > 0){
        SoundListTableViewCell * cell = [SoundListTableViewCell CellWith:tableView];
        [cell.SoundListImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",port,self.voiceListDataArray[indexPath.row - 1].imgUrl]]];
        cell.SoundTitleLabel.text = self.voiceListDataArray[indexPath.row - 1].albumTitle;
        cell.SoundCreatTime.text = [self.voiceListDataArray[indexPath.row - 1].createTime substringToIndex:10];
        cell.SoundPlaytimes.text = [NSString stringWithFormat:@"%d 万",self.voiceListDataArray[indexPath.row - 1].playTimes];
        cell.SoundCurrentTime.text = [NSString stringWithFormat:@"%2d:%2d",self.voiceListDataArray[indexPath.row - 1].duration / 60,self.voiceListDataArray[indexPath.row - 1].duration % 60];
        cell.SoundClassesLabel.text = self.voiceListDataArray[indexPath.row - 1].title;
        cell.selectionStyle = UITableViewCellAccessoryNone;
        return cell;
    }else{
        AlbumDetailSelectTableViewCell * cell = [AlbumDetailSelectTableViewCell fastLogin];
        cell.AlbumTotalNumberLabel.text = [NSString stringWithFormat:@"共 %d 集",self.AlbumDtailModel.voiceTotal];
         cell.selectionStyle = UITableViewCellAccessoryNone;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(infoBtnSelect){
       return UITableViewAutomaticDimension;
    }else if(indexPath.row > 0) {
        return 150.f;
    }else{
        return 44.f;
    }
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
//    [tableView addSubview:button];
//}

-(void)shareAlbumBtnClick{
    __weak typeof(self) weakSelf = self;
    
    // 创建代表每个按钮的模型
    ZYShareItem *item0 = [ZYShareItem itemWithTitle:@"微信朋友圈"
                                               icon:@"Action_Moments"
                                            handler:^{ [weakSelf itemAction:1]; }];
    
    ZYShareItem *item1 = [ZYShareItem itemWithTitle:@"微信好友"
                                               icon:@"share_icon_weixin"
                                            handler:^{ [weakSelf itemAction:2]; }];
    
    ZYShareItem *item2 = [ZYShareItem itemWithTitle:@"新浪微博"
                                               icon:@"share_icon_weibo"
                                            handler:^{ [weakSelf itemAction:3]; }];
    
    ZYShareItem *item3 = [ZYShareItem itemWithTitle:@"QQ"
                                               icon:@"AS_QQ"
                                            handler:^{ [weakSelf itemAction:4]; }];
    
    ZYShareItem *item4 = [ZYShareItem itemWithTitle:@"QQ空间"
                                               icon:@"Action_qzone"
                                            handler:^{ [weakSelf itemAction:5]; }];
    NSArray *shareItemsArray = @[item0, item1, item2, item3];
    NSArray *functionItemsArray = @[item4];
    
    // 创建shareView
    ZYShareView *shareView = [ZYShareView shareViewWithShareItems:shareItemsArray
                                                    functionItems:functionItemsArray];
    // 弹出shareView
    [shareView show];


}
//更多按钮点击事件
- (void)itemAction:(NSInteger)number
{
    switch (number) {
        case 5:
            break;
        default:
            break;
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    // 白色导航栏
    return UIStatusBarStyleLightContent;
}



-(void)moreAlbumBtnClick{
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
